// index.js
// 获取应用实例
const app = getApp()
var api = require("../../utils/api");
var adConfig = require("../../utils/adConfig");


// 在页面中定义激励视频广告
let videoAd = null;
Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    canIUseGetUserProfile: false,
    canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName') ,// 如需尝试获取用户信息可改为false
    showFlag:false,
    mainPicData:{},
    nickImages11:[
      {
      like_image: "https://thirdwx.qlogo.cn/mmopen/vi_32/90xh1INd0mbwHBXPWbWs5TyIqmR7OtlIHWrZ2vdX3sql3dlKyAB1S5NYLGenrr5jUSY1HicmjftYgFCibYPoxJHQ/132"
      },
      {
        like_image: "https://thirdwx.qlogo.cn/mmopen/vi_32/90xh1INd0mbwHBXPWbWs5TyIqmR7OtlIHWrZ2vdX3sql3dlKyAB1S5NYLGenrr5jUSY1HicmjftYgFCibYPoxJHQ/132"
        }
    ]
  },

  onLoad(e) {
    console.log("----" + e.cid)
    this.setData({
      user: wx.getStorageSync('userInfo'),
      userId: wx.getStorageSync('userId'),
      cid:e.cid
  })
  this.getMainPic(this.data.cid);
  this.getMainLike(this.data.cid);


  const that =this;
  //创建广告
  if (wx.createRewardedVideoAd) {
   videoAd = wx.createRewardedVideoAd({
       adUnitId: 'adunit-3ed9a081a6769294'
   })
   videoAd.onLoad(() => { })
   videoAd.onError((err) => {
       wx.showToast({
           title: '广告加载失败，稍后来试哦~',
           icon: 'none'
       })
   })
   videoAd.onClose((res) => {
       if (res && res.isEnded) {
           // 正常播放结束，可以下发游戏奖励
           console.log("正常播放结束")
          that.setData({
           showFlag:true
          })
       } else {
           // 播放中途退出，不下发游戏奖励
           console.log("中途结束")
           wx.showToast({
               title: '你还没完成任务哦，加油~',
               icon: 'none'
           })

       }
   })
  }
  },
  
 //登录服务器
 loginWx: function (data,jsCode) {
  var userInfo =data.userInfo;

  var that = this;
  const accountInfo= wx.getAccountInfoSync()
  const params = {
      appId: accountInfo.miniProgram.appId,
      jsCode: jsCode,
      encryptedData: data.encryptedData,
      iv: data.iv,
  };

  wx.request({
      url: api.wxlogin, //仅为示例，并非真实的接口地址
      method: "POST",
      data: params,
      success(res) {
          console.log(res.data)
          if (res.data.code == 1) {
              wx.setStorageSync('userInfo', res.data.data)
              that.setData({
                  user: res.data.data,
                  userId:res.data.data.id,
                  pointCount:res.data.data.canUsePoint,

              })
              wx.setStorageSync('userId', res.data.data.id)
              wx.setStorageSync('openId', res.data.data.openId)
              wx.setStorageSync('pointCount', res.data.data.canUsePoint)
              wx.showToast({
                  title: '登录成功',
                })
                that.addRecord();
          }else{
              wx.showToast({
                  title: "登录失败,请检查网络",
                  icon: 'none'
              })
          }
      },
      fail:function () {
          wx.showToast({
              title: "登录失败,请检查网络",
              icon: 'none'
          })
      }

  })
},
// 用户授权
getProfile: function (data) {
  var that =this;
  wx.getUserProfile({
    desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
    success: (res) => {
      console.log("res=",res)
      this.setData({
        userInfo: res.userInfo,
        hasUserInfo: true
      })
      wx.login({
        success: res1 => {
            console.log("res1",res1)
            that.loginWx(res, res1.code);

        },
    });

    }
  })
},

addRecord:function(){
  const that =this;
  if(!that.data.user){
    this.getProfile();
    return;
  }

  const params = {
    user_id: that.data.user.id,
    cid: that.data.mainPicData.id,
    title:that.data.mainPicData.title,
    pic_image:that.data.mainPicData.main_image
}

wx.request({
    url: api.addRecord,
    method: "POST",
    data: params,
    success(res) {
        console.log(res.data)
    }
})
},
open:function(){
    // 用户触发广告后，显示激励视频广告
    if (videoAd) {
      videoAd.show().catch(() => {
          // 失败重试
          videoAd.load()
              .then(() => videoAd.show())
              .catch(err => {
                  console.log('激励视频 广告显示失败')
                  wx.showToast({
                      title: '广告加载失败，稍后来试哦~',
                      icon: 'none'
                  })
              })
      })
  }

},

onShareAppMessage: function () {
  return {
    title: "分享你一个秘密花园！"+this.data.mainPicData.title,
    path: "/pages/index/index?cid=" + this.data.mainPicData.code,
    imageUrl: this.data.mainPicData.main_image
  };
},
onShareTimeline: function () {
  return {
      title: "分享你一个秘密花园！"+this.data.mainPicData.title,
      path: "/pages/index/index?cid=" + this.data.mainPicData.code,
      imageUrl: this.data.mainPicData.main_image
  };
},

like:function(){
  const that =this;
  if(!that.data.user){
    this.getProfile();
    return;
  }

  const params = {
    user_id: that.data.user.id,
    like_name: that.data.user.nickName ,
    like_image:that.data.user.headImgUrl,
    cid: that.data.mainPicData.id,
    c_title:that.data.mainPicData.title,
    c_image:that.data.mainPicData.main_image
}

wx.request({
    url: api.likeMainInfo,
    method: "POST",
    data: params,
    success(res) {
        console.log(res.data)
    }
})
},
next:function(){
  this.setData({
    showFlag:false
  })
  this.getMainPic(this.data.mainPicData.afterId)
  this.getMainLike(this.data.mainPicData.afterId)
},
before:function(){
  this.setData({
    showFlag:false
  })
  this.getMainPic(this.data.mainPicData.beforeId)
  this.getMainLike(this.data.mainPicData.beforeId)
},
  getMainPic:function(cid){
    const that =this;
    const params = {
      code: cid
  }

  wx.request({
      url: api.getMainPicInfo,
      method: "POST",
      data: params,
      success(res) {
          console.log(res.data)
          that.setData({
            mainPicData:res.data.data
          })
          if(that.data.user){
            that.addRecord();
          }
      }
  })

  },
  getMainLike:function(cid){
    const that =this;
    const params = {
      mainInfoId: cid
  }

  wx.request({
      url: api.getMainLike,
      method: "POST",
      data: params,
      success(res) {
          console.log(res.data)
          that.setData({
            nickImages:res.data.data
          })

      }
  })

  }
})



